<?php
@header("content-type:text/html;charset=utf-8");

@include_once("conn.php");
@include_once("common.php");//和 mysql数据库建立连接

$key = $_GET["key"];
$orderCol = $_GET["orderCol"];
$orderType = $_GET["orderType"];
$pageIndex = $_GET["pageIndex"];
$showNum = $_GET["showNum"];

if(!($orderCol&&$orderType)){
    paramsErr();
}
$searchAll = "select count(*) as total from `goodslist` where goodsName like '%$key%'";
    $resultAll = mysqli_query($conn,$searchAll);
    if(!$resultAll){  // $result==false 如果sql语句出错  => 阻止脚本继续向后执行
        $obj = array();
        $obj["status"] = false;
        $obj["detail"] = "sql语句有误";
        $obj["sql"] = $searchAll;
        exit(json_encode($obj));
    }

    $item = mysqli_fetch_assoc($resultAll);
    // print_r($item);

    $total = $item["total"]; // 满足条件的总数据

    if($total==0){   // 如果查询数据为0
        $obj = array();
        $obj["status"] = false;
        $obj["detail"] = "暂无数据";
        $obj["sql"] = $searchAll;
        exit(json_encode($obj));
    };

    $maxPage = ceil($total/$showNum);

    if($pageIndex>$maxPage){
        $pageIndex = $maxPage;
    }

    
    if($pageIndex<1){
        $pageIndex = 1;
    }

$skipNum = ($pageIndex-1)*$showNum;
$sql= "select id,goodsId,goodsName,goodsImg,goodsPrice from`goodslist` where goodsName like '%$key%' order by $orderCol $orderType limit $skipNum, $showNum";
$result = mysqli_query($conn,$sql);
if(!$result){  
    $obj = array();
    $obj["status"] = false;
    $obj["detail"] = "sql语句有误";
    $obj["sql"] = $sql;
    exit(json_encode($obj));
}

$all = array();
while($item = mysqli_fetch_assoc($result)){

    // 数据预处理 (将数据返回前端之前  提前做的一些处理)
    // $item["chinese"] = $item["chinese"]*1;
    // $item["math"] = $item["math"]*1;
    // $item["english"] = $item["english"]*1;
    // $item["total"] = $item["total"]*1;
    array_push($all,$item);
   
}

$obj = array();
if(count($all)){ // len > 0 有数据
    $obj["status"] = true;
    $obj["detail"] = "success!";
    $obj["total"]=$total;
    $obj["maxPage"]=$maxPage;
    $obj["list"] = $all;
}else{
    $obj["status"] = false;
    $obj["detail"] = "fail!";
}
echo json_encode($obj);

?>